// Package admin
// Date        : 2023/3/9 15:12
// Version     : 1.0.0
// Author      : 代码小学生王木木
// Email       : 18574945291@163.com
// Description :
package admin

import (
	"errors"
	"gorm.io/gorm"
	"pingbuqingyun_django/app/models/form"
	"pingbuqingyun_django/app/models/form/userForm"
	"pingbuqingyun_django/app/models/response"
	"pingbuqingyun_django/app/models/response/userRespone"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"

	"pingbuqingyun_django/app/config"
	"pingbuqingyun_django/app/models/dao"
	"pingbuqingyun_django/middlewares"
	"pingbuqingyun_django/pkg/tools"
)

type userService struct {
}

var UserService = newUserService()

func newUserService() *userService {
	return &userService{
		//db: tools.DB(),
	}
}

func (u *userService) LoginCheck(username, pwd, loginType string) (*dao.UserModel, error) {
	db := tools.DB()

	var data dao.UserModel
	exist := db.Where(&dao.UserModel{UserName: username}).Or(&dao.UserModel{Phone: username}).First(&data)
	if exist.RowsAffected != 1 {
		return nil, errors.New("用户名/手机号不存在")
	}
	if data.Active == false {
		return nil, errors.New("账号已被禁用")
	}
	if strings.ToLower(loginType) == "cms" && data.IsAdmin == false {
		return nil, errors.New("该账号无登录后台管理权限")
	}
	//if strings.ToLower(loginType) == "wechat" && data.IsAdmin == false {
	//	return nil, errors.New("该账号无登录后台管理权限")
	//}
	//if tools.CheckPwd(data.Password, pwd) {
	//	return &data, nil
	//}
	if pwd == data.Password {
		return &data, nil
	}
	return nil, errors.New("密码错误")
}

func (u *userService) GetToken(user *dao.UserModel) (string, error) {
	jwtCfg := config.ConfigInstance.Jwt
	j := middlewares.NewJwt()
	claims := dao.CustomClaims{
		ID:       uint(user.ID),
		NickName: user.UserName,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),                             // 签名的生效时间
			ExpiresAt: time.Now().Unix() + 3600*jwtCfg.JwtExpireHour, // 签名的过期时间时间
			Issuer:    "",
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		return "", errors.New("生成token失败")
	}
	return token, nil
}

// RegUser
//
//	@Description: 该接口是隐藏接口，不对外暴露
//	@receiver u
//	@param form
//	@return response.RegUserResponse
//	@return error
func (u *userService) RegUser(form *form.RegUserForm) (response.RegUserResponse, error) {
	db := tools.DB()
	var data dao.UserModel
	var res response.RegUserResponse
	exist := db.Where(&dao.UserModel{Phone: form.Phone}).First(&data)
	if exist.RowsAffected >= 1 {
		return res, errors.New("手机号已经存在，无法创建用户")
	}
	data.UserName = form.UserName
	data.Phone = form.Phone
	data.Password = form.Password
	//pwd, err := tools.GeneratePwd(form.Password)
	//if err != nil {
	//	return res, err
	//}
	//data.Password = pwd
	data.Active = true    // 创建的用户默认激活
	data.IsAdmin = true   // 注册的用户默认没有登录后台管理的权限
	data.IsWechat = false // 注册的用户默认没有登录后台管理的权限
	db.Create(&data)
	res.Id = data.ID
	res.UserName = data.UserName
	return res, nil
}

func (u *userService) ChangePermissionService(info userForm.ChangeUserPerForm) error {
	db := tools.DB()
	var data dao.UserModel
	exist := db.Where("id = ?", info.ID).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在无法修改权限")
	}
	if info.PermissionTag == "cms" {
		data.IsAdmin = info.Value
	}
	if info.PermissionTag == "wechat" {
		data.IsWechat = info.Value
	}
	db.Save(&data)
	return nil
}

// CreateUser
//
//	@Description: 管理员新增用户
//	@receiver u
//	@param uid
//	@param form
//	@return response.RegUserResponse
//	@return error
func (u *userService) CreateUser(uid int, form *userForm.CreateUserForm) (response.RegUserResponse, error) {
	db := tools.DB()
	var data dao.UserModel
	var res response.RegUserResponse
	exist := db.Where(&dao.UserModel{Phone: form.Phone}).First(&data)
	if exist.RowsAffected >= 1 {
		return res, errors.New("手机号已经存在，无法创建用户")
	}
	data.UserName = form.UserName
	data.Phone = form.Phone
	//pwd, err := tools.GeneratePwd(form.Password)
	//if err != nil {
	//	return res, err
	//}
	//data.Password = pwd
	data.Password = form.Password
	data.Active = true // 创建的用户默认激活
	// 判断用户是否是小程序还是后台
	switch form.IsAdmin {
	case 1:
		data.IsWechat = true
		break
	case 2:
		data.IsAdmin = true
	case 3:
		data.IsWechat = true
		data.IsAdmin = true
		break
	default:
		break
	}
	data.CreatorId = uid
	db.Create(&data)
	res.Id = data.ID
	res.UserName = data.UserName
	return res, nil
}

// DeactivateUser
//
//	@Description: 禁用用户
//	@receiver u
//	@param uid
//	@param adminId
//	@return error
func (u *userService) DeactivateUser(uid int, adminId int) error {
	db := tools.DB()
	var data, admin dao.UserModel
	exist := db.Where("id = ?", uid).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	exist = db.Where("id = ?", adminId).First(&admin)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	if !admin.IsAdmin {
		return errors.New("权限不足")
	}
	if admin.ID == int64(uid) {
		return errors.New("无法禁用您自己的用户")
	}
	data.Active = false
	db.Save(&data)
	return nil
}

func (u *userService) ActivateUser(uid int, adminId int) error {
	db := tools.DB()
	var data, admin dao.UserModel
	exist := db.Where("id = ?", uid).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	exist = db.Where("id = ?", adminId).First(&admin)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	if !admin.IsAdmin {
		return errors.New("权限不足")
	}
	data.Active = true
	db.Save(&data)
	return nil
}

func (u *userService) ChangePwd(info userForm.ResetPwdForm) error {
	db := tools.DB()
	var data dao.UserModel
	exist := db.Where("id = ?", info.Id).First(&data)
	if exist.RowsAffected != 1 {
		return errors.New("用户不存在")
	}
	if !data.IsAdmin {
		return errors.New("权限不足")
	}
	data.Password = info.Password
	db.Save(&data)
	return nil
}

func PaginateT(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 5
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func (u *userService) SearchUserList(f userForm.UserSearchForm, pageInfo form.PaginateForm) *userRespone.UserListResponses {
	var userList []dao.UserModel
	var res userRespone.UserListResponses
	db := tools.DB()
	//db = db.Scopes(PaginateT(1, 5))
	if len(strings.TrimSpace(f.SearchKey)) != 0 {
		db = db.Where("user_name like ? or phone like ? ", "%"+f.SearchKey+"%", "%"+f.SearchKey+"%")
	}
	if len(strings.TrimSpace(f.CreateDate)) != 0 {
		db = db.Where("create_at >= ?", f.CreateDate)
	}
	if f.UserType == 1 {
		db = db.Where("is_admin = 0")
	}
	if f.UserType == 2 {
		db = db.Where("is_admin = 1")
	}
	if f.UserStatus {
		db = db.Where("active = 0")
	}
	var count int64
	db.Model(&dao.UserModel{}).Count(&count)
	res.Total = count
	db = db.Scopes(PaginateT(int(pageInfo.PageNum), int(pageInfo.PageSize)))
	db.Find(&userList)

	for i := range userList {
		var temp userRespone.UserResponse
		temp.Id = userList[i].ID
		temp.CreateTime = userList[i].CreatedAt.Format("2006-01-02 15:04:05")
		temp.UserName = userList[i].UserName
		temp.Phone = userList[i].Phone
		temp.CoverImgLink = userList[i].CoverImgLink
		temp.Gender = userList[i].Gender
		temp.Active = userList[i].Active
		temp.Password = userList[i].Password
		temp.ShowPwd = false
		temp.IsAdmin = userList[i].IsAdmin
		temp.IsWechat = userList[i].IsWechat
		res.List = append(res.List, temp)
	}
	return &res
}
